var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressJwt = require("express-jwt");
var md5 = require('md5');
var { ForbiddenError, ServiceError, UnknowError } = require("./utils/errors")
var { formatResponse } = require("./utils/tool")
const session =  require("express-session")

// var usersRouter = require('./routes/users');

require("dotenv").config()
require("./dao/db");
require("express-async-errors")


var adminRouter = require('./routes/admin');
var captchaRouter = require('./routes/captcha');
var bannerRouter = require('./routes/banner');
var uploadRouter = require('./routes/upload');


var app = express();

app.use(session({
  secret:process.env.SESSION_SCRET,
  resave:true,
  saveUninitialized:true
}))

// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use(expressJwt({
  secret: md5(process.env.JWT_SECRET),
  algorithms:['HS256']
}).unless({
    path: [{
      url:'/admin/login',
      methods:["POST"]
    },{
      url:'/captcha',
      methods:["GET"]
    },{
      url:'/banner',
      methods:["GET","POST"]
    },{
      url:'/upload',
      methods:["GET","POST"]
    }]
}));

app.use('/admin', adminRouter);
app.use('/captcha',captchaRouter);
app.use('/banner',bannerRouter);
app.use('/upload',uploadRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  console.log(err.message,'msg');
  if (err.name === "UnauthorizedError") {
    res.send(formatResponse(401,"invalid token..."))
  }else if(err instanceof ServiceError){
    res.send(err.toResponseJSON())
  }else{
    res.send(new UnknowError().toResponseJSON())
  }
});

module.exports = app;
